package com.example.iqiyitest.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.iqiyitest.MainActivity;
import com.example.iqiyitest.PlayerActivity;
import com.example.iqiyitest.R;
import com.example.iqiyitest.adapter.DaohangAdapter;
import com.example.iqiyitest.adapter.MovieListAdapter;
import com.example.iqiyitest.adapter.MyMovieAdapter;
import com.example.iqiyitest.adapter.MyMovieAdapter.OnMenuClickListener;
import com.example.iqiyitest.hztvpaysdk.BasePayListenerActivity;
import com.example.iqiyitest.hztvpaysdk.HztvPayUtil;
import com.example.iqiyitest.hztvpaysdk.PayDetail;
import com.example.iqiyitest.hztvpaysdk.PushMessage;
import com.example.iqiyitest.hztvpaysdk.TestActivity;
import com.example.iqiyitest.info.DingDanInfo;
import com.example.iqiyitest.info.MovieDetailInfo;
import com.example.iqiyitest.info.ResultDingdanInfo;
import com.example.iqiyitest.listener.Detaillistener;
import com.example.iqiyitest.utils.HttpClient;
import com.example.iqiyitest.utils.ImageLoader;
import com.example.iqiyitest.view.MyItemDecoration;
import com.example.iqiyitest.view.MyItemDecoration.OrientationType;
import com.google.gson.Gson;
import com.example.iqiyitest.view.ScaleRecyclerView;
import com.iqiyi.movieksdk.sdk.exported.Constants;
import com.iqiyi.movieksdk.sdk.exported.HttpResult;
import com.iqiyi.movieksdk.sdk.exported.IMsgReceiver;
import com.iqiyi.movieksdk.sdk.exported.LogUtils;
import com.iqiyi.movieksdk.sdk.exported.MovieSdk;
import com.iqiyi.movieksdk.sdk.exported.OnResponseListener;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class DetailForMovieActivity extends Activity implements IMsgReceiver,Detaillistener {
	ImageView detail_img;
	TextView detail_name, detail_score, detail_director, detail_actor, detail_videoType, detail_description;
	static MovieDetailInfo datainfo;
	String TAG = "iqiyitest";
	private ImageLoader mImageLoader;
	private MovieSdk movieSdk;
	private String host = "192.168.1.241";// 正式
	private long testQipuId = 723849600;// 仙球大战
	private ScaleRecyclerView secondMenuRecy;
	ArrayList<MovieDetailInfo> moviedetailInfos;
	private OnMenuClickListener menuClickListener;
	private MyMovieAdapter recyclerAdapter;
	private MyItemDecoration itemDecoration;
	private LinearLayoutManager lineManager;
	Button bofang;
	static Button fufei;
	protected Map<String, String> queryPara = new HashMap<String, String>();
	String getVideosUrl="http://120.26.71.181/manage/port/iqiyiPrice";
	String movie_type;//付费模式
	String movie_flag;//是否付费
	DingDanInfo dindanInfo;//订单数据
	String movie_order;//订单号
	public static boolean ifplay=false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_detaiformovie);
		moviedetailInfos = new ArrayList<MovieDetailInfo>();
		movieSdk = MovieSdk.init(getApplication(), com.example.iqiyitest.base.Constants.serviceUrl, new MovieSdk.OnInitListener() {
			@Override
			public void initOver(int code) {
				Toast.makeText(DetailForMovieActivity.this, "init code:" + code, Toast.LENGTH_SHORT).show();
			}
		});
		movieSdk.addMsgReceiver(this);
		mImageLoader = ImageLoader.getInstance();// zhangzhl--后进先出法 ，优先加载 最后一个
		Intent intent;
		if (getIntent() != null) {
			intent = getIntent();
			datainfo = (MovieDetailInfo) intent.getExtras().getSerializable("data");
			Log.e("iqiyitest", datainfo.toString());
		}
		detail_img = (ImageView) findViewById(R.id.detail_img);
		detail_name = (TextView) findViewById(R.id.detail_name);
		detail_score = (TextView) findViewById(R.id.detail_score);
		detail_director = (TextView) findViewById(R.id.detail_director);
		detail_actor = (TextView) findViewById(R.id.detail_actor);
		detail_videoType = (TextView) findViewById(R.id.detail_videoType);
		detail_description = (TextView) findViewById(R.id.detail_description);
		secondMenuRecy = (ScaleRecyclerView) findViewById(R.id.second_recycler);
		bofang = (Button) findViewById(R.id.button1);
		fufei = (Button) findViewById(R.id.button2);
		init();
		getDingdanInfo();
	}

	public void getDingdanInfo() {
		queryPara.clear();
		queryPara.put("vpn", "10.8.1.70:8000");
		queryPara.put("hotel", "pomics");
		queryPara.put("room", "201");
		queryPara.put("id", "969086700");
		
		HttpClient.post(getVideosUrl, queryPara, new HttpClient.CallBack() {

			@Override
			public void onSuccess(String json) {
				if (json != null && !"".equals(json)) {
					Log.e("iqiyitest222222222222",json);
					ResultDingdanInfo res = null;
					try {
						res = HttpClient.gson.fromJson(json, ResultDingdanInfo.class);
						movie_type=res.getType();
						movie_flag=res.getFlag();
						com.example.iqiyitest.base.Constants.setMovie_flag(movie_flag);
						movie_order=res.getOrder();
						dindanInfo=res.getInfo().get(0);
						Message m = new Message();
						m.what=1;
						splashHandler.sendMessage(m);
					} catch (Exception e) {
						e.printStackTrace();
					}
					
				}
			}

			@Override
			public void onFailure(String msg) {
				LogUtils.e(TAG, msg);
			}
		});

	}
	public void refulshView() {
		if(com.example.iqiyitest.base.Constants.getMovie_flag().equals("2")) {
			fufei.setVisibility(View.GONE);
			// 播放
					// TODO Auto-generated method stub
			Intent intent = new Intent(DetailForMovieActivity.this, PlayMovieActivity.class);
			intent.putExtra("qipuId", Long.valueOf(datainfo.getQipuId()));
			intent.putExtra("playType", Constants.MODE_NEW);
			startActivity(intent);
		}
	}
	private Handler splashHandler = new Handler() {
	     public void handleMessage(Message msg) {
	       switch (msg.what) {
	       case 1:
	    	   if(movie_flag.equals("1")){
	    		   fufei.setVisibility(View.VISIBLE);
	    		// 付费
	    			fufei.setOnClickListener(new View.OnClickListener() {

	    				@Override
	    				public void onClick(View v) {
	    					// TODO Auto-generated method stub
	    					  HztvPayUtil.init(getApplication(),"1a71400d-33d9-4b15-ad76-fcf0c8f4b07f","6a002f9f-55ca-4100-bc1a-704939f82d6b");
	    					  com.example.iqiyitest.base.Constants.setMovie_activity("DetailForMovieActivity");
	    					  PayDetail payDetail = new PayDetail();
	    		                //订单号，有调用业务传递
	    		                payDetail.order.AppOrderId=movie_order;
	    		                //订单名称
	    		                payDetail.order.OrderName="爱奇艺视频24小时畅看包";
	    		                //订单描述信息
	    		                payDetail.order.OrderDesc="包天";
	    		                //订单金额
//	    		                payDetail.order.TxnAmount=Double.valueOf(dindanInfo.getBppirce());
	    		                payDetail.order.TxnAmount=Double.valueOf("0.01");//测试
	    		                
	    		                //订单类型,eg:VOD,固定值
	    		                payDetail.order.OrderType="VOD";
	    		                //供应商名称，固定值
	    		                payDetail.order.SupplyIdentity="XSHUAI";
	    		                HztvPayUtil.startToPay(DetailForMovieActivity.this, payDetail);
	    				}
	    			});
	    	   }else {
	    		   fufei.setVisibility(View.GONE);
	    	   }
	        break;
	       case 2:
	    	   break;
	       default:
	           break;
	       }
	          super.handleMessage(msg);
	     }
	};
	@Override
	protected void onDestroy() {
		super.onDestroy();
		movieSdk.removeMsgReceiver(this);
	}

	public void init() {
		// 播放
		bofang.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(DetailForMovieActivity.this, PlayMovieActivity.class);
				intent.putExtra("qipuId", Long.valueOf(datainfo.getQipuId()));
				intent.putExtra("playType", Constants.MODE_NEW);
				startActivity(intent);
			}
		});
		if (datainfo.getPosterLocalImg() != null && !datainfo.getPosterLocalImg().equals("")) {
			mImageLoader.loadImage(datainfo.getPosterLocalImg(), detail_img, true);
		}
		if (datainfo.getDisplayName() != null && !datainfo.getDisplayName().equals("")) {
			detail_name.setText(datainfo.getDisplayName());
		}
		if (datainfo.getScore() != 0) {
			detail_score.setText("评分  :" + datainfo.getScore());
		}
		if (datainfo.getDirector() != null && !datainfo.getDirector().equals("")) {
			detail_director.setText(datainfo.getDirector());
		}
		if (datainfo.getActor() != null && !datainfo.getActor().equals("")) {
			detail_actor.setText(datainfo.getActor());
		}
		if (datainfo.getVideoType() != null && !datainfo.getVideoType().equals("")) {
			detail_videoType.setText(datainfo.getVideoType());
		}
		if (datainfo.getDescription() != null && !datainfo.getDescription().equals("")) {
			detail_description.setText(datainfo.getDescription());
		}
		// 获取推荐影片
		movieSdk.sdk_getRelatedMovieRecom(datainfo.getQipuId(), 10, new OnResponseListener() {
			@Override
			public void onResponse(HttpResult result) {
				Log.d(TAG, result.data);
				// text.setText(result.data);
				try {
					JSONArray jsonArray = new JSONArray(result.data);
					JSONObject jsonObject;
					MovieDetailInfo movieDetailInfo;
					for (int i = 0; i < jsonArray.length(); i++) {
						jsonObject = jsonArray.getJSONObject(i);
						movieDetailInfo = new MovieDetailInfo();
						movieDetailInfo.setPosterLocalImg(jsonObject.optString("posterLocalImg"));
						movieDetailInfo.setDuration(jsonObject.optInt("duration"));
						movieDetailInfo.setShotDesc(jsonObject.optString("shotDesc"));
						movieDetailInfo.setDescription(jsonObject.optString("description"));
						movieDetailInfo.setScore(jsonObject.optInt("score"));
						movieDetailInfo.setShowTime(jsonObject.optInt("showtime"));
						movieDetailInfo.setPlayType(jsonObject.optString("playType"));
						movieDetailInfo.setPlayTimes(jsonObject.optInt("playTimes"));
						movieDetailInfo.setActor(jsonObject.optString("actor"));
						movieDetailInfo.setQipuId(jsonObject.optInt("qipuId"));
						movieDetailInfo.setDirector(jsonObject.optString("director"));
						movieDetailInfo.setDisplayName(jsonObject.optString("displayName"));
						movieDetailInfo.setVideoType(jsonObject.optString("videoType"));
						moviedetailInfos.add(movieDetailInfo);
					}
					recyclerAdapter = new MyMovieAdapter(DetailForMovieActivity.this, R.layout.item_second_activity,
							moviedetailInfos, menuClickListener);
					itemDecoration = new MyItemDecoration(0xffffff, dip2px(DetailForMovieActivity.this, 20), 0,
							OrientationType.HORIZONTAL);

					GridLayoutManager gridManager = new GridLayoutManager(DetailForMovieActivity.this, 5);
					gridManager.setOrientation(LinearLayoutManager.VERTICAL);

					lineManager = new LinearLayoutManager(DetailForMovieActivity.this);
					lineManager.setOrientation(LinearLayoutManager.HORIZONTAL);

					secondMenuRecy.setLayoutManager(lineManager);
					secondMenuRecy.setAdapter(recyclerAdapter);
					secondMenuRecy.addItemDecoration(itemDecoration);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

		menuClickListener = new OnMenuClickListener() {

			@Override
			public void onClick(int position, View v) {
				MovieDetailInfo movieDetailInfo = moviedetailInfos.get(position);
				Log.e(TAG, movieDetailInfo.toString());
				Intent intent = new Intent(DetailForMovieActivity.this, DetailForMovieActivity.class);
				Bundle bundle = new Bundle();
				bundle.putSerializable("data", movieDetailInfo);
				intent.putExtras(bundle);
				startActivity(intent);
				DetailForMovieActivity.this.finish();
			}
		};
	}

	/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 */
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	@Override
	public void onReceived(final String s) {
		Toast.makeText(this, "msg:" + s, Toast.LENGTH_SHORT).show();
		Log.d(TAG, "msg" + s);
		// text.post(new Runnable() {
		// @Override
		// public void run() {
		// text.setText("收到消息："+s);
		// }
		// });

	}
	public static void play() {
		Log.e("fufeitest", "付费成功playplayplayplayplayplay");
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if(ifplay) {
			if(com.example.iqiyitest.base.Constants.getMovie_flag().equals("1")) {
				fufei.setVisibility(View.VISIBLE);
			}else {
				fufei.setVisibility(View.GONE);
				Intent intent = new Intent(DetailForMovieActivity.this, PlayMovieActivity.class);
				intent.putExtra("qipuId", Long.valueOf(datainfo.getQipuId()));
				intent.putExtra("playType", Constants.MODE_NEW);
				startActivity(intent);
				ifplay=false;
				Log.e("fufeitest", "付费成功");
			}
		}else {
			
		}
	}
}
